package com.yearEndWorkload.listen;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yearEndWorkload.mapper.*;
import com.yearEndWorkload.pojo.entity.SpecializedChild;
import com.yearEndWorkload.pojo.entity.SpecializedWork;
import com.yearEndWorkload.pojo.excel.importTemplate.SpecialWorkExcel;

import com.yearEndWorkload.pojo.vo.BaseOutstandingTreeVo;
import com.yearEndWorkload.pojo.vo.OutstandingPerformanceVo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Data
public class SpecialWorkExcelListener implements ReadListener<SpecialWorkExcel> {

    private static final int BATCH_COUNT = 100;
    //================需要使用set方法注入下列内容==============================//
    private SpecializedChildMapper specializedChildMapper;
    private SpecializedWorkMapper specializedWorkMapper;

    //------------------------------------------------------//
    private TypeStandardMapper typeStandardMapper;
    //excel表缓存，可不使用，减少内存占有。
//    private List<SpecialWorkExcel> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    //存入数据库的缓存信息。
    private List<SpecializedWork> specializedWorkList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private List<SpecializedChild> specializedChildList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);


    //记录 父id 和 项目负责人之间的映射关系
    private Map<String, Integer> mapForParent = new HashMap<>();

    //保存未正确保存的数据。
    private List<SpecialWorkExcel> unSave = new ArrayList<>();

    //保存的信息。
    private List<BaseOutstandingTreeVo> outstandingTreeVoList;

    //判断是否存在父
    private boolean isLiveNewOutstandingParent(SpecializedWork specializedWork ) {

        QueryWrapper<SpecializedWork> queryWrapper = new QueryWrapper<>();
        Map<String,Object> map = new HashMap<>();
        map.put("year",specializedWork.getYear());
        map.put("workload_type",specializedWork.getWorkloadType());
        map.put("project_context",specializedWork.getProjectContext());
        map.put("score",specializedWork.getScore());
        map.put("responsible_person",specializedWork.getResponsiblePerson());

        queryWrapper.allEq(map);


        boolean exists = specializedWorkMapper.exists(queryWrapper);

        return !exists;
    }

    //判断是否存在子
    private boolean isLiveNewOutstandingChild() {

        return true;
    }


    //查询判断较比，存在一摸一样的年终业绩情况就不允许导入。


    @Override
    public void invoke(SpecialWorkExcel SpecialWorkExcel, AnalysisContext analysisContext) {

        System.out.println("1");

        log.info("解析到一条有效数据:{}", JSON.toJSONString(SpecialWorkExcel));
        //采用先存父表的策略。
        if (SpecialWorkExcel != null) {

            String teacherName = SpecialWorkExcel.getTeacherName();
            String responsiblePerson = SpecialWorkExcel.getResponsiblePerson();
            if (teacherName.equals(responsiblePerson)) {
                //构造父表插入元素
                SpecializedWork specializedWork = new SpecializedWork();
                specializedWork.setYear(SpecialWorkExcel.getYear());
                specializedWork.setWorkloadType(SpecialWorkExcel.getWorkloadType());
                specializedWork.setProjectContext(SpecialWorkExcel.getProjectContext());
                specializedWork.setScore(SpecialWorkExcel.getScore());
                specializedWork.setResponsiblePerson(SpecialWorkExcel.getResponsiblePerson());
                specializedWork.setReporter(SpecialWorkExcel.getReporter());

                boolean liveNewOutstandingParent = isLiveNewOutstandingParent(specializedWork);
                if (liveNewOutstandingParent) {
                    specializedWorkMapper.insert(specializedWork);
                    BaseOutstandingTreeVo baseOutstandingTreeVo = new BaseOutstandingTreeVo();
                    OutstandingPerformanceVo outstandingPerformanceVo = new OutstandingPerformanceVo();

                    BeanUtil.copyProperties(specializedWork, outstandingPerformanceVo);
                    //TODO 获取存下的内容。

                    //

                    mapForParent.put(responsiblePerson, specializedWork.getId());

                } else {
                    unSave.add(SpecialWorkExcel);
                }

            } else {
                SpecializedChild specializedChild = new SpecializedChild();

                //获取projectId
                Integer projectId = mapForParent.get(responsiblePerson);

                if(projectId!=null){
                    specializedChild.setProjectId(projectId);
                    specializedChild.setScore(SpecialWorkExcel.getScore());
                    specializedChild.setTeacherName(SpecialWorkExcel.getTeacherName());
                    if (isLiveNewOutstandingChild()) {
                        specializedChildList.add(specializedChild);
                    }

                }else {
                    unSave.add(SpecialWorkExcel);
                }
            }

        }

        //子表满了就批量保存。
        if (specializedChildList.size() >= BATCH_COUNT) {
            saveNewOutstandingChildData();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("000");
        saveNewOutstandingChildData();
        log.info("解析完成");
    }


    //子表存
    private void saveNewOutstandingChildData() {
        if (specializedChildList.size() > 0) {
            specializedChildMapper.insertByBatch(specializedChildList);
        }
    }
}
